package com.safeneeds.util.page.dao.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;

import com.safeneeds.util.base.BaseHibernateDao;
import com.safeneeds.util.other.StringUtil;
import com.safeneeds.util.page.dao.IPageDao;

/**
 * 
 * 基于Hiberntae的分页实现
 * 
 * @version 1.0
 * @date 2016-04-26
 * @author gaof
 */
public class PageDao extends BaseHibernateDao<Object, Integer> implements IPageDao {

	public int getTotalCountByHbSql(String hbSql) {
		return this.count(hbSql);
	}

	@SuppressWarnings("rawtypes")
	public List getRangeInfoList(String hbSql, int page, int pageSize) {
		return this.getEntitiesPage(hbSql, page, pageSize);
	}
	
	/**
	 * 本地化sql语句接口,获得记录数目
	 * @param totalCountHbSQL
	 * @return
	 */
	public int getTotalCountBySql(String Sql){
		
		Session session = currentSession();
		Object temp = session.createSQLQuery(Sql).uniqueResult();
		
		//count = (BigDecimal) temp;
		
		/*HttpSession session = request.getSession();
		BigInteger count = new BigInteger("0");

		try {
			Object temp = session.createSQLQuery(Sql).uniqueResult();
			count = (BigInteger) temp;
		} finally {
			releaseSession(session);
			
		}*/

		return StringUtil.StringToInt(temp.toString(), 0);
	}
	
	/**
	 * 获取分页记录信息
	 * 
	 * @param hbSql
	 *            :查询语句
	 * @param page
	 *            :要查询的页数
	 * @param pageSize
	 *            :一页显示的数量
	 * @param entityClass
	 *            :查询结果映射实体
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List getSQLRangeInfoList(String hbSql, int page,
			int pageSize, Class entityClass){
		
		List list = null;
		Session session = currentSession();
		if(entityClass != null){//需要将查询结果转换成实体
			
			list = session.createSQLQuery(hbSql).addEntity(entityClass).setFirstResult(
					(page - 1) * pageSize).setMaxResults(pageSize).list();
			
		}else{
			
			list = session.createSQLQuery(hbSql).setFirstResult(
					(page - 1) * pageSize).setMaxResults(pageSize).list();
		}
		
		if (null == list) {
			list = new ArrayList();
		}
		
		return list;
	}

}
